package net.tv90.shoppingserver.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import net.tv90.shoppingserver.model.domain.Good;
import net.tv90.shoppingserver.model.dto.GoodAddDTO;
import net.tv90.shoppingserver.model.dto.GoodQueryDTO;
import net.tv90.shoppingserver.service.GoodService;
import net.tv90.shoppingserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Validated
@CrossOrigin
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodService goodService;

    @Autowired
    UserService userService;

    @PostMapping("/add")
    @SaCheckLogin
    public String addGood(GoodAddDTO dto) {
        goodService.addGood(dto);
        return "";
    }

    @GetMapping("/query")
    public String queryGoods(GoodQueryDTO dto, Model model) {
        handleUserNameModel(model);
        List<Good> goods = goodService.queryGoods(dto);
        Integer num = goodService.queryNum(dto);
        model.addAttribute("num", num);
        model.addAttribute("goods", goods);
        model.addAttribute("dto", dto);
        return "index";
    }

    @GetMapping("/detail/{id}")
    public String getDetailById(@PathVariable("id") Integer id, Model model) {
        handleUserNameModel(model);
        Good good = goodService.queryGoodById(id);
        model.addAttribute("good", good);
        return "goodDetail";
    }

    private void handleUserNameModel(Model model) {
        String username = userService.getCurrentUserName();
        if (username != null) {
            model.addAttribute("username", username);
        }
    }
}